<?php
class Helper_Encoder {
	
	/**
	 * crypt encoder
	 *
	 * @param string $key
	 * @param string $plain_text
	 * @return string encoded text
	 */
	function encrypt($key, $plain_text) {
		$plain_text = trim ( $plain_text );
		$iv = substr ( md5 ( $key ), 0, mcrypt_get_iv_size ( MCRYPT_CAST_256, MCRYPT_MODE_CFB ) );
		$c_t = mcrypt_cfb ( MCRYPT_CAST_256, $key, $plain_text, MCRYPT_ENCRYPT, $iv );
		return trim ( chop ( base64_encode ( $c_t ) ) );
	}
	
	/**
	 * crypt decoder
	 *
	 * @param string $key
	 * @param string $c_t the text need for decode
	 * @return string decoded text
	 */
	function decrypt($key, $c_t) {
		$c_t = trim ( chop ( base64_decode ( $c_t ) ) );
		$iv = substr ( md5 ( $key ), 0, mcrypt_get_iv_size ( MCRYPT_CAST_256, MCRYPT_MODE_CFB ) );
		$p_t = mcrypt_cfb ( MCRYPT_CAST_256, $key, $c_t, MCRYPT_DECRYPT, $iv );
		return trim ( chop ( $p_t ) );
	}
	
	/**
	 * Encode text safly 
	 *
	 * @param string $string
	 * @param string $outEncoding (utf-8|gbk...)
	 * @return string encoded text
	 */
	function safeEncode($string, $outEncoding = 'UTF-8') {
		$encoding = "UTF-8";
		for($i = 0; $i < strlen ( $string ); $i ++) {
			if (ord ( $string {$i} ) < 128)
				continue;
			if ((ord ( $string {$i} ) & 224) == 224) {
				//第一个字节判断通过  
				$char = $string {++ $i};
				if ((ord ( $char ) & 128) == 128) {
					//第二个字节判断通过  
					$char = $string {++ $i};
					if ((ord ( $char ) & 128) == 128) {
						$encoding = "UTF-8";
						break;
					}
				}
			}			
			if ((ord ( $string {$i} ) & 192) == 192) {
				//第一个字节判断通过  
				$char = $string {++ $i};
				if ((ord ( $char ) & 128) == 128) {
					//第二个字节判断通过  
					$encoding = "GB2312";
					break;
				}
			}
		}
		
		if (strtoupper ( $encoding ) == strtoupper ( $outEncoding ))
			return $string;
		else
			return iconv ( $encoding, $outEncoding, $string );
	
	}
}
?>